import React, { useState, useEffect } from 'react';
import { Card, Typography, Table, Button, Space, Modal, Form, Input, Select, Slider, Tag } from 'antd';
import { EditOutlined, DeleteOutlined, PlusOutlined, MinusCircleOutlined } from '@ant-design/icons';
import '../../styles/transparentTable.css';

const { Title } = Typography;

const PositionStrategy: React.FC = () => {
  const [isInterModalVisible, setIsInterModalVisible] = useState(false);
  const [isIntraModalVisible, setIsIntraModalVisible] = useState(false);
  const [isEdit, setIsEdit] = useState(false);
  const [currentStrategy, setCurrentStrategy] = useState<any>(null);
  const [interForm] = Form.useForm();
  const [intraForm] = Form.useForm();
  
  // 模式间仓位分配状态
  const [valueLowPosition, setValueLowPosition] = useState(3); // 价值低吸仓位
  const [bandCompoundPosition, setBandCompoundPosition] = useState(3); // 波段复利仓位
  const [mainLeaderPosition, setMainLeaderPosition] = useState(2); // 主线龙头仓位
  const [speculativeArbitragePosition, setSpeculativeArbitragePosition] = useState(2); // 投机套利仓位
  
  // 市场条件数组
  const [marketConditions, setMarketConditions] = useState<string[]>(['牛市']);
  
  // 模式内仓位分配状态
  const [intraCashRatio, setIntraCashRatio] = useState(4); // 模式内现金比例，默认4成
  const [intraPosition, setIntraPosition] = useState(6); // 模式内仓位，默认6成
  
  // 模式内市场条件数组
  const [intraMarketConditions, setIntraMarketConditions] = useState<string[]>(['震荡市']);

  const showInterModal = (edit: boolean, strategy?: any) => {
    setIsEdit(edit);
    setCurrentStrategy(strategy || null);
    if (edit && strategy) {
      interForm.setFieldsValue(strategy);
      // 设置仓位数据
      setValueLowPosition(parseInt(strategy.valueLowPosition) || 3);
      setBandCompoundPosition(parseInt(strategy.bandCompoundPosition) || 3);
      setMainLeaderPosition(parseInt(strategy.mainLeaderPosition) || 2);
      setSpeculativeArbitragePosition(parseInt(strategy.speculativeArbitragePosition) || 2);
      setMarketConditions(strategy.marketConditions || ['牛市']);
    } else {
      interForm.resetFields();
      // 重置仓位数据
      setValueLowPosition(3);
      setBandCompoundPosition(3);
      setMainLeaderPosition(2);
      setSpeculativeArbitragePosition(2);
      setMarketConditions(['牛市']);
    }
    setIsInterModalVisible(true);
  };

  const showIntraModal = (edit: boolean, strategy?: any) => {
    setIsEdit(edit);
    setCurrentStrategy(strategy || null);
    if (edit && strategy) {
      intraForm.setFieldsValue(strategy);
      // 设置模式内仓位数据
      setIntraCashRatio(parseInt(strategy.cashRatio) || 4);
      setIntraPosition(parseInt(strategy.position) || 6);
      setIntraMarketConditions(strategy.marketConditions || ['震荡市']);
    } else {
      intraForm.resetFields();
      // 重置模式内仓位数据
      setIntraCashRatio(4);
      setIntraPosition(6);
      setIntraMarketConditions(['震荡市']);
    }
    setIsIntraModalVisible(true);
  };

  const handleInterOk = () => {
    interForm.validateFields().then((values) => {
      const formData = {
        ...values,
        marketConditions,
        valueLowPosition: `${valueLowPosition}成`,
        bandCompoundPosition: `${bandCompoundPosition}成`,
        mainLeaderPosition: `${mainLeaderPosition}成`,
        speculativeArbitragePosition: `${speculativeArbitragePosition}成`,
        totalPosition: `${allocatedPosition}成`
      };
      console.log('模式间策略表单值:', formData);
      setIsInterModalVisible(false);
    }).catch((info) => {
      console.log('模式间策略验证失败:', info);
    });
  };

  const handleIntraOk = () => {
    intraForm.validateFields().then((values) => {
      const formData = {
        ...values,
        marketConditions: intraMarketConditions,
        cashRatio: `${intraCashRatio}成`,
        position: `${intraPosition}成`,
      };
      console.log('模式内策略表单值:', formData);
      setIsIntraModalVisible(false);
    }).catch((info) => {
      console.log('模式内策略验证失败:', info);
    });
  };

  const handleInterCancel = () => {
    setIsInterModalVisible(false);
  };

  const handleIntraCancel = () => {
    setIsIntraModalVisible(false);
  };
  // 计算已分配仓位
  const allocatedPosition = valueLowPosition + bandCompoundPosition + mainLeaderPosition + speculativeArbitragePosition;
  
  // 计算剩余可分配仓位（总仓位固定为10成）
  const remainingPosition = 10 - allocatedPosition;
  
  // 添加市场条件
  const addMarketCondition = () => {
    setMarketConditions([...marketConditions, '']);
  };
  
  // 删除市场条件
  const removeMarketCondition = (index: number) => {
    if (marketConditions.length > 1) {
      const newConditions = marketConditions.filter((_, i) => i !== index);
      setMarketConditions(newConditions);
    }
  };
  
  // 更新市场条件
  const updateMarketCondition = (index: number, value: string) => {
    const newConditions = [...marketConditions];
    newConditions[index] = value;
    setMarketConditions(newConditions);
  };
  
  // 仓位变化处理函数
  const handlePositionChange = (type: string, value: number) => {
    const currentAllocated = valueLowPosition + bandCompoundPosition + mainLeaderPosition + speculativeArbitragePosition;
    const otherPositionsSum = currentAllocated - (type === 'valueLow' ? valueLowPosition : 
                                                  type === 'bandCompound' ? bandCompoundPosition :
                                                  type === 'mainLeader' ? mainLeaderPosition : speculativeArbitragePosition);
    
    // 确保新值不超过剩余可分配额度（总仓位固定为10成）
    const maxAllowed = 10 - otherPositionsSum;
    const finalValue = Math.min(value, maxAllowed);
    
    switch (type) {
      case 'valueLow':
        setValueLowPosition(finalValue);
        break;
      case 'bandCompound':
        setBandCompoundPosition(finalValue);
        break;
      case 'mainLeader':
        setMainLeaderPosition(finalValue);
        break;
      case 'speculativeArbitrage':
        setSpeculativeArbitragePosition(finalValue);
        break;
    }
  };

  // 计算每个仓位的动态最大值
  const getMaxValue = (type: string) => {
    const currentAllocated = valueLowPosition + bandCompoundPosition + mainLeaderPosition + speculativeArbitragePosition;
    const currentValue = type === 'valueLow' ? valueLowPosition : 
                        type === 'bandCompound' ? bandCompoundPosition :
                        type === 'mainLeader' ? mainLeaderPosition : speculativeArbitragePosition;
    const otherPositionsSum = currentAllocated - currentValue;
    return 10 - otherPositionsSum;
  };

  // 模式内市场条件处理函数
  // 添加模式内市场条件
  const addIntraMarketCondition = () => {
    setIntraMarketConditions([...intraMarketConditions, '']);
  };
  
  // 删除模式内市场条件
  const removeIntraMarketCondition = (index: number) => {
    if (intraMarketConditions.length > 1) {
      const newConditions = intraMarketConditions.filter((_, i) => i !== index);
      setIntraMarketConditions(newConditions);
    }
  };
  
  // 更新模式内市场条件
  const updateIntraMarketCondition = (index: number, value: string) => {
    const newConditions = [...intraMarketConditions];
    newConditions[index] = value;
    setIntraMarketConditions(newConditions);
  };

  // 模式间仓位分配策略数据
  const interModeData = [
    {
      key: '1',
      marketCondition: '牛市',
      emotionCycle: '上升期',
      name: '策略A',
      valueLowPosition: '3成',
      bandCompoundPosition: '3成',
      mainLeaderPosition: '2成',
      speculativeArbitragePosition: '2成',
    },
  ];

  // 模式内仓位分配策略数据
  const intraModeData = [
    {
      key: '1',
      tradeMode: '波段复利',
      name: '策略B',
      marketCondition: '震荡市',
      cashRatio: '40%',
      position: '60%',
    },
  ];

  // 模式间仓位分配策略列
  const interModeColumns = [
    { title: '序号', dataIndex: 'key', key: 'key' },
    { title: '市场条件', dataIndex: 'marketCondition', key: 'marketCondition' },
    { title: '情绪周期阶段', dataIndex: 'emotionCycle', key: 'emotionCycle' },
    { title: '名称', dataIndex: 'name', key: 'name' },
    { title: '价值低吸仓位', dataIndex: 'valueLowPosition', key: 'valueLowPosition' },
    { title: '波段复利仓位', dataIndex: 'bandCompoundPosition', key: 'bandCompoundPosition' },
    { title: '主线龙头仓位', dataIndex: 'mainLeaderPosition', key: 'mainLeaderPosition' },
    { title: '投机套利仓位', dataIndex: 'speculativeArbitragePosition', key: 'speculativeArbitragePosition' },
    {
      title: '操作',
      key: 'action',
      render: (_, record:any) => (
        <Space size="middle">
          <Button type="text" icon={<EditOutlined style={{ color: '#64ffda' }} />} onClick={() => showInterModal(true, record)} />
          <Button type="text" icon={<DeleteOutlined style={{ color: '#64ffda' }} />} />
        </Space>
      ),
    },
  ];

  // 模式内仓位分配策略列
  const intraModeColumns = [
    { title: '序号', dataIndex: 'key', key: 'key' },
    { title: '交易模式', dataIndex: 'tradeMode', key: 'tradeMode' },
    { title: '名称', dataIndex: 'name', key: 'name' },
    { title: '市场条件', dataIndex: 'marketCondition', key: 'marketCondition' },
    { title: '现金', dataIndex: 'cashRatio', key: 'cashRatio' },
    { title: '仓位', dataIndex: 'position', key: 'position' },
    {
      title: '操作',
      key: 'action',
      render: (_, record) => (
        <Space size="middle">
          <Button type="text" icon={<EditOutlined style={{ color: '#64ffda' }} />} onClick={() => showIntraModal(true, record)} />
          <Button type="text" icon={<DeleteOutlined style={{ color: '#64ffda' }} />} />
        </Space>
      ),
    },
  ];

  return (
    <div style={{ padding: '20px', backgroundColor: '#0a192f', minHeight: '100vh' }}>
      {/* 上方区域 - 模式间仓位分配策略 */}
      <Card
        title="模式间仓位分配策略"
        style={{ backgroundColor: 'rgba(17, 34, 64, 0.8)', borderColor: '#233554', marginBottom: '20px' }}
        headStyle={{ backgroundColor: 'rgba(17, 34, 64, 0.8)', borderBottomColor: '#233554', color: '#64ffda' }}
        bodyStyle={{ backgroundColor: 'rgba(17, 34, 64, 0.8)', color: '#ccd6f6' }}
        extra={<Button type="primary" onClick={() => showInterModal(false)}>新建模式间仓位策略</Button>}
      >
        <Table
          columns={interModeColumns}
          dataSource={interModeData}
          pagination={false}
          style={{ color: '#ccd6f6', backgroundColor: 'transparent', border: 'none' }}
          className="transparent-table"
        />
      </Card>

      {/* 下方区域 - 模式内仓位分配策略 */}
      <Card
        title="模式内仓位分配策略"
        style={{ backgroundColor: 'rgba(17, 34, 64, 0.8)', borderColor: '#233554' }}
        headStyle={{ backgroundColor: 'rgba(17, 34, 64, 0.8)', borderBottomColor: '#233554', color: '#64ffda' }}
        bodyStyle={{ backgroundColor: 'rgba(17, 34, 64, 0.8)', color: '#ccd6f6' }}
        extra={<Button type="primary" onClick={() => showIntraModal(false)}>新建模式内仓位策略</Button>}
      >
        <Table
          columns={intraModeColumns}
          dataSource={intraModeData}
          pagination={false}
          style={{ color: '#ccd6f6', backgroundColor: 'transparent', border: 'none' }}
          className="transparent-table"
        />
      </Card>

      <Modal
        title={isEdit ? '编辑模式间策略' : '新建模式间策略'}
        visible={isInterModalVisible}
        onOk={handleInterOk}
        onCancel={handleInterCancel}
        width={900}
      >
        <Form form={interForm} layout="vertical">
          <Form.Item name="name" label="策略名称" rules={[{ required: true, message: '请输入策略名称' }]}>
            <Input />
          </Form.Item>
          
          <Form.Item label="市场条件">
            {marketConditions.map((condition, index) => (
              <div key={index} style={{ display: 'flex', marginBottom: '8px', alignItems: 'center' }}>
                <Input
                  value={condition}
                  onChange={(e) => updateMarketCondition(index, e.target.value)}
                  placeholder="请输入市场条件"
                  style={{ marginRight: '8px' }}
                />
                {marketConditions.length > 1 && (
                  <Button
                    type="text"
                    icon={<MinusCircleOutlined />}
                    onClick={() => removeMarketCondition(index)}
                    style={{ color: '#ff4d4f' }}
                  />
                )}
              </div>
            ))}
            <Button
              type="dashed"
              onClick={addMarketCondition}
              icon={<PlusOutlined />}
              style={{ width: '100%', marginTop: '8px' }}
            >
              添加市场条件
            </Button>
          </Form.Item>

          <Form.Item name="emotionCycle" label="情绪周期阶段">
            <Input placeholder="请输入情绪周期阶段" />
          </Form.Item>
          
          {/* 持仓显示 */}
          <div style={{ marginBottom: '16px', padding: '12px', backgroundColor: '#f5f5f5', borderRadius: '6px' }}>
            <span style={{ fontWeight: 'bold', color: '#1890ff' }}>
              总仓位: 10成 | 已分配: {allocatedPosition}成 | 剩余: {remainingPosition}成
            </span>
          </div>
          
          {/* 价值低吸仓位滑动条 */}
          <Form.Item label={`价值低吸仓位: ${valueLowPosition}成 (最大: ${getMaxValue('valueLow')}成)`}>
            <Slider
              min={0}
              max={getMaxValue('valueLow')}
              value={valueLowPosition}
              onChange={(value) => handlePositionChange('valueLow', value)}
              marks={Object.fromEntries(Array.from({length: getMaxValue('valueLow') + 1}, (_, i) => [i, `${i}成`]))}
              step={1}
            />
          </Form.Item>
          
          {/* 波段复利仓位滑动条 */}
          <Form.Item label={`波段复利仓位: ${bandCompoundPosition}成 (最大: ${getMaxValue('bandCompound')}成)`}>
            <Slider
              min={0}
              max={getMaxValue('bandCompound')}
              value={bandCompoundPosition}
              onChange={(value) => handlePositionChange('bandCompound', value)}
              marks={Object.fromEntries(Array.from({length: getMaxValue('bandCompound') + 1}, (_, i) => [i, `${i}成`]))}
              step={1}
            />
          </Form.Item>
          
          {/* 主线龙头仓位滑动条 */}
          <Form.Item label={`主线龙头仓位: ${mainLeaderPosition}成 (最大: ${getMaxValue('mainLeader')}成)`}>
            <Slider
              min={0}
              max={getMaxValue('mainLeader')}
              value={mainLeaderPosition}
              onChange={(value) => handlePositionChange('mainLeader', value)}
              marks={Object.fromEntries(Array.from({length: getMaxValue('mainLeader') + 1}, (_, i) => [i, `${i}成`]))}
              step={1}
            />
          </Form.Item>
          
          {/* 投机套利仓位滑动条 */}
          <Form.Item label={`投机套利仓位: ${speculativeArbitragePosition}成 (最大: ${getMaxValue('speculativeArbitrage')}成)`}>
            <Slider
              min={0}
              max={getMaxValue('speculativeArbitrage')}
              value={speculativeArbitragePosition}
              onChange={(value) => handlePositionChange('speculativeArbitrage', value)}
              marks={Object.fromEntries(Array.from({length: getMaxValue('speculativeArbitrage') + 1}, (_, i) => [i, `${i}成`]))}
              step={1}
            />
          </Form.Item>
          
          {/* 仓位分配警告 */}
          {remainingPosition < 0 && (
            <div style={{ color: '#ff4d4f', marginBottom: '16px', padding: '8px', backgroundColor: '#fff2f0', borderRadius: '4px' }}>
              ⚠️ 仓位分配超出限制，请调整各仓位比例
            </div>
          )}
        </Form>
      </Modal>

      <Modal
        title={isEdit ? '编辑模式内策略' : '新建模式内策略'}
        visible={isIntraModalVisible}
        onOk={handleIntraOk}
        onCancel={handleIntraCancel}
        width={800}
      >
        <Form form={intraForm} layout="vertical">
          <Form.Item name="name" label="策略名称" rules={[{ required: true, message: '请输入策略名称' }]}>
            <Input />
          </Form.Item>
          
          <Form.Item name="tradeMode" label="交易模式" rules={[{ required: true, message: '请选择交易模式' }]}>
            <Select placeholder="请选择交易模式">
              <Select.Option value="波段复利">波段复利</Select.Option>
              <Select.Option value="主线龙头">主线龙头</Select.Option>
              <Select.Option value="投机套利">投机套利</Select.Option>
              <Select.Option value="价值低吸">价值低吸</Select.Option>
            </Select>
          </Form.Item>
          
          {/* 模式内市场条件多项输入 */}
          <Form.Item label="市场条件" required>
            <div style={{ marginBottom: '8px' }}>
              {intraMarketConditions.map((condition, index) => (
                <div key={index} style={{ display: 'flex', marginBottom: '8px', alignItems: 'center' }}>
                  <Input
                    value={condition}
                    onChange={(e) => updateIntraMarketCondition(index, e.target.value)}
                    placeholder="请输入市场条件"
                    style={{ marginRight: '8px' }}
                  />
                  {intraMarketConditions.length > 1 && (
                    <Button
                      type="text"
                      icon={<MinusCircleOutlined />}
                      onClick={() => removeIntraMarketCondition(index)}
                      style={{ color: '#ff4d4f' }}
                    />
                  )}
                </div>
              ))}
              <Button
                type="dashed"
                onClick={addIntraMarketCondition}
                icon={<PlusOutlined />}
                style={{ width: '100%' }}
              >
                添加市场条件
              </Button>
            </div>
          </Form.Item>
          
          {/* 现金比例滑动条 */}
          <Form.Item label={`现金: ${intraCashRatio}成`}>
            <Slider
              min={0}
              max={10}
              value={intraCashRatio}
              onChange={(value) => {
                setIntraCashRatio(value);
                setIntraPosition(10 - value);
              }}
              marks={{
                0: '0成',
                1: '1成',
                2: '2成',
                3: '3成',
                4: '4成',
                5: '5成',
                6: '6成',
                7: '7成',
                8: '8成',
                9: '9成',
                10: '10成'
              }}
              step={1}
            />
          </Form.Item>
          
          {/* 仓位滑动条 */}
          <Form.Item label={`仓位: ${intraPosition}成`}>
            <Slider
              min={0}
              max={10}
              value={intraPosition}
              onChange={(value) => {
                setIntraPosition(value);
                setIntraCashRatio(10 - value);
              }}
              marks={{
                0: '0成',
                1: '1成',
                2: '2成',
                3: '3成',
                4: '4成',
                5: '5成',
                6: '6成',
                7: '7成',
                8: '8成',
                9: '9成',
                10: '10成'
              }}
              step={1}
            />
          </Form.Item>
          
          {/* 总仓位显示 */}
          <div style={{ marginBottom: '16px', padding: '12px', backgroundColor: '#f5f5f5', borderRadius: '6px' }}>
            <span style={{ fontWeight: 'bold', color: '#1890ff' }}>
              总仓位: {intraCashRatio + intraPosition}成 (现金: {intraCashRatio}成 + 仓位: {intraPosition}成)
            </span>
          </div>
          
          {/* 仓位分配警告 */}
          {intraCashRatio + intraPosition !== 10 && (
            <div style={{ color: '#ff4d4f', marginBottom: '16px', padding: '8px', backgroundColor: '#fff2f0', borderRadius: '4px' }}>
              ⚠️ 现金与仓位总和必须等于10成
            </div>
          )}
        </Form>
      </Modal>
    </div>
  );
};

export default PositionStrategy;
